package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AdminFilter implements Ordered, GlobalFilter {

    //登录校验是否放行
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 判断是否为登录操作,是则放行
        if (request.getURI().getPath().contains("/login")) {
            return chain.filter(exchange);
        }

        //3. 其他操作(除去登录之外) 先获取token判断是否合法并且是否被更改
        String token = request.getHeaders().getFirst("token");
        //3.1 判断token是否存在 为空返回未登录
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //3.2 判断token是否合法
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //是否过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //获取登录用户的id
            String adminId = claimsBody.get("id").toString();

            //对请求对象request进行增强
            ServerHttpRequest req = request.mutate().headers(httpHeaders -> {
                //httpHeaders 封装了所有的请求头
                httpHeaders.set("adminId", adminId);
            }).build();

            //设置增强的request到exchange对象中
            exchange.mutate().request(req);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return chain.filter(exchange);
    }


    /**
     * 网关过滤器优先级控制
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
